<?php

namespace Biz\service;

use Biz\model\GoodsBasicInfo;
use Biz\model\ShopAdorn as mShopAdorn;
use Biz\model\ShopSwitch;
use Biz\pockets\constInterface\ActivityInfo;
use Doraemon\model\Member as mMember;
use Biz\service\brand\Brand;
use Doraemon\service\Search;
use Doraemon\service\User;
use Doraemon\tools\Log as tLog;
use Biz\model\ShopBasicInfo as mShopBasicInfo;
use Doraemon\tools\HhzClient as tHhzClient;
use Biz\service\Goods as sGoods;
use Doraemon\tools\Log;
use Biz\service\esSearch\Goods as esSearch;

class BrandUser
{
    const BRAND_USER_TYPE_A = 1;
	const BRAND_USER_TYPE_B = 2;
	const BRAND_USER_TYPE_C = 3;
	const BRAND_USER_TYPE_D = 4;

	const DEFAULT_PAGESIZE = 20;
	/**
	 * 根据UID获取 品牌账户的类型
	 * @param $uid
	 * @return int
	 * @throws \Exception
	 *
	 */
	public static function getBrandUserType($uid)
	{
		$userInfo = User::getUserInfo($uid);
		if ($userInfo['type'] == mMember::AUTH_USER_BRAND) {
			$shopInfo = ShopInfo::getShopInfo($uid, [], 'app');
			$is_has_shop  = isset($shopInfo['shop_id']) && $shopInfo['status'] != mShopBasicInfo::STATUS_CLOSED ? true : false;
			$brand_id = self::getUserBrandId($uid) ;

			$is_bind_brand = $brand_id ? true : false;
			$is_has_goods = $brand_id ?  GoodsBasicInfo::is_has_goods($brand_id) : false;

			if ($is_has_shop && $is_bind_brand) {
				return self::BRAND_USER_TYPE_B;
			}
			if ($is_has_shop && !$is_bind_brand) {
				return self::BRAND_USER_TYPE_C;
			}

			if ((!$is_has_shop && !$is_bind_brand) || ($is_bind_brand && !$is_has_goods)) {
				return self::BRAND_USER_TYPE_A;
			}
			if (!$is_has_shop && $is_bind_brand && $is_has_goods) {
				return self::BRAND_USER_TYPE_D;
			}

			tLog::NOTICE(['uid' => $uid, 'type_status' => [$is_has_shop, $is_bind_brand, $is_has_goods]]);

			throw new \Exception('非正常类型品牌用户');
		 } else {
			throw new \Exception('非品牌用户');
		}

	}
	/**
	 * 获取用户绑定的 brandID
	 * @param $uid
	 *
	 */
	public static function getUserBrandId($uid, $withTile = false)
	{
		$info = Search::searchByField('search_mod', 'brand', ['uid' => $uid, 'fl' => ['id', 'brand']]);
		$brand_id = 0;
		if ($info['total'] > 0) {
			$brand_id = $info['rows'][0]['id'];
			$brand_name = $info['rows'][0]['brand'];
		}

		if ($withTile) {
			return [$brand_id, $brand_name];
		} else {
			return $brand_id;
		}
	}
	/**
	 *
     *  废弃了吧？
     * @deprecated
	 * 品牌详情页 品牌详情  接口调用
	 * @param $uid
	 * @param $current_uid
	 * @return array
	 * @throws \Exception
	 *
	 */
	public static function BrandUserInfo($uid, $current_uid)
	{
		$shopInfo = ShopInfo::getShopInfo($uid, ['info','identifyImageList'], 'app');
		$counter = User::get_counter($uid);
		$userInfo = User::getUserInfo($uid, true, $current_uid);
		$brandId = self::getUserBrandId($uid);
		$brandInfo  =  $brandId ?  Brand::getBrandInfoById($brandId) : [];
		$brandUserInfo = array_merge($userInfo, ['brand_type' => self::getBrandUserType($uid)]);
		$brandUserInfo = array_merge($brandUserInfo, ['shop_info' => $shopInfo]);
		$brandUserInfo = array_merge($brandUserInfo, ['counter' => $counter]);
		$brandUserInfo = array_merge($brandUserInfo, ['brand_info' => $brandInfo]);

		$identifyImgList = isset($brandUserInfo['shop_info']['identifyImageList']['basic']) && $brandUserInfo['shop_info']['identifyImageList']['basic'] ? array_column($brandUserInfo['shop_info']['identifyImageList']['basic'], null ,'key') : [];

		return  [
			'uid' => $brandUserInfo['uid'],
			'nick' => $brandUserInfo['nick'],
			'avatar' => $brandUserInfo['avatar'],
			'cover_img' => $brandUserInfo['cover_img'],
			'big_avatar' => $brandUserInfo['big_avatar'],
			'remark' => $brandUserInfo['remark'],
			'type' => $brandUserInfo['type'],
			'is_follow' => $brandUserInfo['is_follow'],
			'is_follow_new' => $brandUserInfo['is_follow_new'],
			'brand_type' => $brandUserInfo['brand_type'],
			'shop_info' => in_array($brandUserInfo['brand_type'] , [self::BRAND_USER_TYPE_A, self::BRAND_USER_TYPE_D]) ? null : [
				'uid' => $brandUserInfo['shop_info']['uid'],
				'shop_id' => $brandUserInfo['shop_info']['shop_id'],
				'name' => $brandUserInfo['shop_info']['name'],
				'type' => $brandUserInfo['shop_info']['type'],
				'realname' => isset( $brandUserInfo['shop_info']['info']['name']) ? $brandUserInfo['shop_info']['info']['name'] : $brandUserInfo['shop_info']['info']['realname'],
				'intro' => str_replace('，请帮忙填写吧', '',$brandUserInfo['shop_info']['intro']) ,
				'imgurl' => $brandUserInfo['shop_info']['imgurl'],
                'shop_icon' => $brandUserInfo['shop_info']['imgurl'],
				'score' => in_array($brandUserInfo['brand_type'], [self::BRAND_USER_TYPE_B, self::BRAND_USER_TYPE_C]) ?  $brandUserInfo['shop_info']['score'] : '0.0',
				'business_license' => isset($identifyImgList['business_license']) ? $identifyImgList['business_license'] : (object)[],
			],
			'counter' => $brandUserInfo['counter'],
			'brand_info' => $brandUserInfo['brand_info'],
			'share_info' => User::getUserInfoForApp($uid, $current_uid)['share_info']
		];

	}

    public static function getAllGoods($uid = 0, $bannerIdOrGoodsIdsList = '', $areaCode, $orderType, $appVersion = null, $page = 1, $pagesize = self::DEFAULT_PAGESIZE)
    {
        $Rst = [
            'list'    => (array)[],
            'is_over' => 1,
        ];
        $brandType = '';
        if ($uid) {
            if(is_array($bannerIdOrGoodsIdsList)){
                $map = ['id'=>$bannerIdOrGoodsIdsList];
            }else{
                $brandType = self::getBrandUserType($uid);
                if ($brandType == self::BRAND_USER_TYPE_A) {
                    return $Rst;
                }
                if (in_array($brandType, [self::BRAND_USER_TYPE_B, self::BRAND_USER_TYPE_C])) {
                    $map = ['shop_id' => $uid];
                }
                if ($brandType == self::BRAND_USER_TYPE_D) {
                	if (ShopInfo::getShopInfoList([$uid])[$uid]['status'] == mShopBasicInfo::STATUS_CLOSED) {
						return $Rst;
					}
                    list($brandId, $brandName) = self::getUserBrandId($uid, true);
                    $map = ['brand_id' => $brandId];
                }
            }
        } else {
            $goodsids = mShopAdorn::getGoodsIds($bannerIdOrGoodsIdsList);
            $map = ['id' => $goodsids];
        }
        $map['source'] = esSearch::SOURCE_APP;
        if (SearchGoods::isInDouble11() && $uid && !is_array($bannerIdOrGoodsIdsList) && $orderType == 0) {
        	$map['activity'] = esSearch::ACTIVITY_TYPE_CHANGE_PRICE_ACTIVITY;
			$result  = SearchGoods::searchEntrance($map, esSearch::SCENES_BRAND_ALL_GOODS, $orderType, $page, $pagesize);
			if ($result['is_over']) {
				$preGoodsIds = $result['rows'];
				unset($map['activity']);
				$map['activity[!]'] = [esSearch::ACTIVITY_TYPE_CHANGE_PRICE_ACTIVITY];
				$page = $page - floor($result['total']/$pagesize);
				$result  = SearchGoods::searchEntrance($map, esSearch::SCENES_BRAND_ALL_GOODS, $orderType, $page, $pagesize);
				$result['rows'] = array_merge($preGoodsIds, $result['rows']);
			}
		} else {
			$result  = SearchGoods::searchEntrance($map,esSearch::SCENES_BRAND_ALL_GOODS, $orderType, $page, $pagesize);
		}
        $params = ['area_code' => $areaCode];
        if ($appVersion && version_compare($appVersion, '3.16.0', "<")) {
           $params["not_activity_type"] = [ActivityInfo::ACTIVITY_TYPE_PINTUAN];
        }

		$goodsInfos = Goods::Goods($result['rows'], Goods::FIELDS_GROUP_LIST, $params);
		foreach ($goodsInfos as $goodsId => &$goodsInfo)
		{
			$goodsInfos[$goodsId]['reminder'] = $brandType == self::BRAND_USER_TYPE_D ? '来自 ' . $goodsInfo['shop_info']['name'] : '';
		}
		$Rst['list'] = $goodsInfos;

		$Rst['is_over'] = $result['is_over'];
		$Rst['list'] = array_values($Rst['list']);
		return $Rst;
	}


	public static function HotGoodsList($uid, $is_force = 0, $areaCode = 0,$pagesize = self::DEFAULT_PAGESIZE)
	{
		if (!$uid) {
			throw new \Exception('未获取 UID');
		}
		if (!$is_force && !ShopSwitch::is_show_hotGoods($uid)) {
			return (array)[];
		}
        $where = [
            'shop_id' => $uid,
            'tags_content[!]' => esSearch::GOODS_TAG_SHIELD,
            'source' => esSearch::SOURCE_APP
        ];

		if ($uid == 4372030) {
		    $where['category_id'] = 1;
            $results = SearchGoods::searchEntrance($where,esSearch::SCENES_BRAND_HOT_GOODS, 0, 1, $pagesize);
            // todo 搜索切换es待删除
//			$results = searchGoods::searchByConditions(['shop_id' => $uid, 'sort' => ['sell_total' => 'DESC'], 'tags_content' => ['not' => searchGoods::GOODS_TAG_SHIELD], 'query' => ' cate_id:1'], 0, 1, $pagesize);
			if (!$results['rows']) {
			    unset($where['AND']['category_id']);
			    $where['AND']['category_id[!]'] = 401;
                $results = SearchGoods::searchEntrance($where, esSearch::SCENES_BRAND_HOT_GOODS,0, 1, $pagesize);
                // todo 搜索切换es待删除
//				$results = searchGoods::searchByConditions(['shop_id' => $uid, 'sort' => ['sell_total' => 'DESC'], 'tags_content' => ['not' => searchGoods::GOODS_TAG_SHIELD], 'query' => ' !cate_id:401'], 0, 1, $pagesize);
			}
		} else {
            $where['AND']['category_id[!]'] = 401;
            $results = SearchGoods::searchEntrance($where, esSearch::SCENES_BRAND_HOT_GOODS,0, 1, $pagesize);
            // todo 搜索切换es待删除
//			$results = SearchGoods::searchByCommon(['shop_id' => $uid, 'sort' => ['sell_total' => 'DESC'], 'tags_content' => ['not' => searchGoods::GOODS_TAG_SHIELD], 'query' => ' !cate_id:401'], 0, 1, $pagesize);
		}
		$Rst = sGoods::Goods($results['rows'], sGoods::FIELDS_GROUP_LIST, ['area_code' => $areaCode]);

		return array_values($Rst);

	}

	public static function GoodsList($brand_id, $areaCode, $sort_type = 0, $page, $pagesize = self::DEFAULT_PAGESIZE)
	{
		if (!$brand_id) {
			throw new \Exception('brandid为空');
		}
		$sort_type_map = [
			[
				'sell_total' => 'DESC',
				'addtime' => 'ASC',
			],
			[
				'addtime' => 'DESC',
			]
		];
		$Rst = [
			'list' => (array) [],
			'is_over' => 1
		];
		$goodsBasicInfos = GoodsBasicInfo::getInfos([
			'brand_id' => $brand_id,
			'had_online' => GoodsBasicInfo::HAD_ONLINE_YES,
			'status' => GoodsBasicInfo::$statusAppCanSeeMap,
			'ORDER' => $sort_type_map[$sort_type],
			'LIMIT' => [($page - 1) * $pagesize, $pagesize]
		]);
		if ($goodsBasicInfos) {
			$goods_ids = array_column($goodsBasicInfos, 'goods_id');
			$goodsInfos = GoodsDetail::FormatBasicInfoOnGoodsInfoList($goods_ids, $areaCode);
			$goodsInfos_online = [];
			$goodsInfos_offline = [];
			foreach ($goodsInfos as $goodsInfo) {
				if ($goodsInfo['status'] == GoodsBasicInfo::STATUS_APP_NOMAL) {
					$goodsInfos_online[] = $goodsInfo;
				} else {
					$goodsInfos_offline[] = $goodsInfo;
				}
			}
			$Rst['list'] = array_merge($goodsInfos_online, $goodsInfos_offline);
			$Rst['is_over'] = count($Rst['list']) < $pagesize ?  1 : 0;
		}

		return $Rst;
	}


}